package com.itboye.pondteam.pondteam;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hiflying.smartlink.ISmartLinker;
import com.hiflying.smartlink.OnSmartLinkListener;
import com.hiflying.smartlink.SmartLinkedModule;
import com.hiflying.smartlink.v7.MulticastSmartLinker;
import com.itboye.pondteam.R;
import com.itboye.pondteam.app.MyApplication;
import com.itboye.pondteam.base.BaseActivity;
import com.itboye.pondteam.bean.DeviceDetailModel;
import com.itboye.pondteam.bean.SearchDeviceInfo;
import com.itboye.pondteam.custom.ActivityInputWifiAndPass;
import com.itboye.pondteam.db.DBManager;
import com.itboye.pondteam.interfaces.SmartConfigType;
import com.itboye.pondteam.presenter.UserPresenter;
import com.itboye.pondteam.utils.Const;
import com.itboye.pondteam.utils.loadingutil.MAlert;
import com.itboye.pondteam.volley.ResultEntity;

import java.util.Observable;
import java.util.Observer;

import static com.itboye.pondteam.utils.EmptyUtil.getSp;


/**
 * Created by Mr.w on 2017/3/4.
 */

public class ActivityStepThree extends BaseActivity implements Observer, OnSmartLinkListener {
    TextView btn_next, txt_title;
    int position;
    String did;
    UserPresenter userPresenter;
    boolean hasFind = false;
    private DeviceDetailModel model;
    String wifiName = "";
    String wifiPass = "";

    String req = "{\"req\":\"device_info\"}";
    String str = "";
    Gson gson = new Gson();
    ProgressDialog loadingDialog = null;
    protected ISmartLinker mSnifferSmartLinker;
    private SearchDeviceInfo searchDeviceInfo;
    MyApplication mApp;
    AlertDialog.Builder alert;
    boolean isBusy = false;
    ImageView img_back;
    DBManager dbManager;

    SmartConfigType smartConfigType;

    ImageView img_finish_search, img_finish_register, img_finish_add;
    TextView txt_search, txt_register, txt_add;
    ProgressBar progress_search, progress_register, progress_add;
    RelativeLayout re_search, re_register, re_add;
    boolean isRessBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_step_three);
        mSnifferSmartLinker = MulticastSmartLinker.getInstance();
        mApp = (MyApplication) getApplication();
        mApp.addDeviceThird = this;
        alert = new AlertDialog.Builder(this);
        dbManager = new DBManager(this);
        smartConfigType = SmartConfigType.SEARCHING;
        setZhuangTai(smartConfigType);
        position = getIntent().getIntExtra("position", 0);
        wifiName = getIntent().getStringExtra("wifi_name");
        wifiPass = getIntent().getStringExtra("wifi_pass");
//        did = getIntent().getStringExtra("did");
        txt_title.setText(getString(R.string.add_device));
        txt_search.setText(getString(R.string.searching) + "");
        loadingDialog = new ProgressDialog(this);
        loadingDialog.setTitle(getString(R.string.tips));
        loadingDialog.setMessage(getString(R.string.peizhiing));
        loadingDialog.setCanceledOnTouchOutside(false);
        loadingDialog.show();
        loadingDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    isRessBack = true;
                    mSnifferSmartLinker.stop();
                }
                return true;
            }
        });
        userPresenter = new UserPresenter(this);
        isBusy = false;
//        mProgressDialog.setMessage("正在获取配置中，请稍后。。。");
//        mProgressDialog.setTitle("提示信息");
//        mProgressDialog.show();
        switch (position) {
            case 0:
                break;
            case 1:
                break;
            case 2:
                break;
            case 3:
//                userPresenter.getDeviceGuoLvTongStatus(did);
                break;
            case 4:
                break;
            case 5:
//                userPresenter.getDeviceMostNew(did);
                break;
            case 6:
                break;
            case 7:
                break;
            case 8:
                break;
        }
        mSnifferSmartLinker.setOnSmartLinkListener(this);
        //开始 smartLink
        try {
            mSnifferSmartLinker.start(getApplicationContext(), wifiPass,
                    wifiName);
        } catch (Exception e) {
            closeProgressDialog();
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        mSnifferSmartLinker.stop();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_next:
                if (smartConfigType == SmartConfigType.ADD_FINISH) {
                    mApp.addPondDeviceUI.finish();
                    mApp.deviceListActivityUI.getMyDeviceList();
                    finish();
                    return;
                }
                if (smartConfigType == SmartConfigType.RESEARCH) {
                    isBusy = false;
                    smartConfigType = SmartConfigType.SEARCHING;
                    setZhuangTai(smartConfigType);
                    loadingDialog.setMessage(getString(R.string.searching));
                    loadingDialog.show();
                    try {
                        mSnifferSmartLinker.start(getApplicationContext(), wifiPass,
                                wifiName);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return;
                }
                if (hasFind == false || searchDeviceInfo == null) {
                    MAlert.alert(getString(R.string.deviceid_error));
                    return;
                }
                if (hasAdd(searchDeviceInfo.getDid())) {
                    MAlert.alert(getString(R.string.hasAdd));
                    return;
                }
                smartConfigType = SmartConfigType.ADDING;
                setZhuangTai(smartConfigType);
                ActivityInputWifiAndPass.getInstance().finish();
                ActivityStepFirst.getInstance().finish();
                userPresenter.addDevice(getSp(Const.UID), searchDeviceInfo.getDid(), searchDeviceInfo.getRes());
                break;
            case R.id.img_back:
                finish();
                break;
        }
    }

    /**
     * 检测是否已经添加过该设备
     *
     * @param did
     * @return
     */
    private boolean hasAdd(String did) {
        boolean isAdd = false;
        if (mApp.mDeviceUi.arrayList != null) {
            for (int i = 0; i < mApp.mDeviceUi.arrayList.size(); i++) {
                if (did.equals(mApp.mDeviceUi.arrayList.get(i).getDid())) {
                    isAdd = true;
                    break;
                } else {
                    isAdd = false;
                }
            }
        }
        return isAdd;
    }


    @Override
    public void update(Observable o, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getCode() != 0) {
                MAlert.alert(entity.getMsg());
                txt_search.setText(getString(R.string.deviceid_error) + "");
                return;
            }
            if (entity.getEventType() == UserPresenter.getdeviceinfosuccess) {
                hasFind = true;
                model = (DeviceDetailModel) entity.getData();
//                if (model.getIs_disconnect().equals("1")) {
//                    txt_search.setText(getString(R.string.disconnect) + "");
////                    img_finish_search.setVisibility(View.VISIBLE);
//                    hasFind = false;
//                } else {
                hasFind = true;
                smartConfigType = SmartConfigType.ADD_FINISH;
                setZhuangTai(smartConfigType);
//                }
            } else if (entity.getEventType() == UserPresenter.getdeviceinfofail) {
                smartConfigType = SmartConfigType.RESEARCH;
                setZhuangTai(smartConfigType);
                txt_search.setText(getString(R.string.research) + "");
                hasFind = false;
                MAlert.alert(entity.getData());
            } else if (entity.getEventType() == UserPresenter.adddevice_success) {
                MAlert.alert(entity.getData());
                mApp.deviceListActivityUI.getMyDeviceList();//设备劣列表页面应该重新获取数据

                dbManager.insertDeviceData(searchDeviceInfo.getDid(), searchDeviceInfo.getPwd(),getSp(Const.UID));
                mApp.addDeviceFirst.finish();//关闭第一步页面
//                mApp.addDeviceUI.finish();//关闭添加设备类型页面
                mApp.addDeviceInputWifi.finish();//关闭输入ssid页面
                finish();
            } else if (entity.getEventType() == UserPresenter.adddevice_fail) {
                MAlert.alert(entity.getData());
            }
        }
    }

    @Override
    public void onLinked(SmartLinkedModule smartLinkedModule) {
        loadingDialog.setMessage(getString(R.string.get_configing));//获取
        smartConfigType = SmartConfigType.SEARCH_FINISH;
        setZhuangTai(smartConfigType);
        smartConfigType = SmartConfigType.REGISTERING;
        setZhuangTai(smartConfigType);
    }

    @Override
    public void onCompleted() {
//        new Thread(runnable).start();
        isBusy = true;
        smartConfigType = SmartConfigType.REGISTER_FINISH;
        setZhuangTai(smartConfigType);
        loadingDialog.setMessage(getString(R.string.smartconfig_finish));
    }


    public void setZhuangTai(SmartConfigType smartConfigType) {
        switch (smartConfigType) {
            case SEARCHING://搜索中
                btn_next.setText(getString(R.string.searching));
                txt_search.setText(getString(R.string.searching));
                re_search.setVisibility(View.VISIBLE);
                img_finish_search.setVisibility(View.GONE);
                progress_search.setVisibility(View.VISIBLE);
                break;
            case SEARCH_FINISH://搜索完成
                re_search.setVisibility(View.VISIBLE);
                img_finish_search.setVisibility(View.VISIBLE);
                progress_search.setVisibility(View.GONE);
                break;
            case REGISTERING://注册中
                btn_next.setText(getString(R.string.registering));
                txt_register.setText(getString(R.string.registering));
                re_register.setVisibility(View.VISIBLE);
                img_finish_register.setVisibility(View.GONE);
                progress_register.setVisibility(View.VISIBLE);
                break;
            case REGISTER_FINISH://注册完成
                btn_next.setText(getString(R.string.next));
                txt_register.setText(getString(R.string.registerfinsh));
                re_register.setVisibility(View.VISIBLE);
                img_finish_register.setVisibility(View.VISIBLE);
                progress_register.setVisibility(View.GONE);
                break;
            case ADDING://添加中
                btn_next.setText(getString(R.string.adding));
                txt_add.setText(getString(R.string.adding));
                re_add.setVisibility(View.VISIBLE);
                img_finish_add.setVisibility(View.VISIBLE);
                progress_add.setVisibility(View.GONE);
                break;
            case ADD_FINISH://添加完成
                btn_next.setText(getString(R.string.close));
                txt_add.setText(getString(R.string.addfinsh));
                re_add.setVisibility(View.VISIBLE);
                img_finish_add.setVisibility(View.VISIBLE);
                progress_add.setVisibility(View.GONE);
                break;
            case RESEARCH://重新搜索
                progress_search.setVisibility(View.GONE);
                btn_next.setText(getString(R.string.research));
                re_search.setVisibility(View.VISIBLE);
                re_register.setVisibility(View.GONE);
                re_add.setVisibility(View.GONE);
                break;
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSnifferSmartLinker.stop();
    }

    @Override
    public void onTimeOut() {
        if (!isRessBack) {
            MAlert.alert(getString(R.string.timeout));
            txt_search.setText(getString(R.string.timeout));
        } else {
            MAlert.alert(getString(R.string.configuration_stop));
            txt_search.setText(getString(R.string.configuration_stop));
            isRessBack = false;
        }
        loadingDialog.dismiss();
        smartConfigType = SmartConfigType.RESEARCH;
        setZhuangTai(smartConfigType);
        btn_next.setText(getString(R.string.research) + "");
    }

    public void findNewDeviceInfo(SearchDeviceInfo deviceInfo) {

        this.searchDeviceInfo = deviceInfo;
        // 查空
        if (deviceInfo == null) {
            return;
        }
        //还未配置成功
        if (!isBusy) {
            return;
        }
        isBusy = false;
        did = deviceInfo.getDid();
        img_finish_search.setVisibility(View.VISIBLE);
        // 只处理正在配置中的状态
//        if (!mBusy) {
//            return;
//        }
        // 停止配置
//        stopConfig();
        // 添加设备
//        mApp.addDevice(deviceInfo);
        // 提示新设备
        hasFind = true;
        loadingDialog.dismiss();
        alert.setTitle(getString(R.string.tips));
        alert.setMessage(getString(R.string.find_new_device) + " DID : \n" + deviceInfo.getDid());
        alert.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 停止配置
                isRessBack = true;
                mApp.addDeviceThird = null;
                mSnifferSmartLinker.stop();
//                        Intent intent = new Intent(ActivityStepThree.this, DeviceActivity.class);
//                        startActivity(intent);
//                        finish();
            }
        });
        alert.show();
    }
}
